package com.xu.chuang.show.ui;



import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.xu.chuang.show.R;
import com.xu.chuang.show.bean.Content;
import com.xu.chuang.show.bean.ContextType;
import com.xu.chuang.show.bean.ShowUser;
import com.xu.chuang.show.network.SyncRequest;
import com.xu.chuang.show.service.impl.MainBizReqImpl;
import com.xu.chuang.show.service.inte.MainBizReqService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AMapV2地图中介绍定位三种模式的使用，包括定位，追随，旋转
 */
public class WingActivity extends AppCompatActivity implements LocationSource,
        AMapLocationListener, AMap.OnMarkerClickListener,
        AMap.OnMapLoadedListener, AMap.OnInfoWindowClickListener {

    public static final String ARG_PARAM = "param";

    public static final String ARG_PARAMContent = "content";

    public static final String PARAM_LAT = "param_lat";

    public static final String PARAM_LOG = "param_lon";

    private AMap aMap;

    private MapView mapView;

    private OnLocationChangedListener mListener;

    private AMapLocationClient mLocationClient;

    private MainBizReqService mainBizReqService = new MainBizReqImpl();

    private ShowUser showUser;

    private List<Content> contentList;

    private Map<Marker, Content> markerRelationContentMap = new HashMap<>();

    private Double localLatitude;

    private Double localLongitude;

    private Boolean locationGet = false;

    private AMapLocation allMapLocation;

    private ContextType contextType;

    private Boolean allType = true;

    List<Content> userContentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wing);
        SyncRequest.syncReq();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        showUser = (ShowUser) bundle.get(ARG_PARAM);

        userContentList = mainBizReqService.findUserContent(showUser.getShowUserId());

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.love_share));
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.inflateMenu(R.menu.menu_drawer_main);
        Menu navMenu  = navigationView.getMenu();

        int length = 0;
        for(Content content : userContentList) {
            String contextString = content.getContext();
            if(contextString.length()>10){
                contextString= contextString.substring(0,10) + "...";
            }
            length++;
            if(length == 1) {
                MenuItem menuItem = navMenu.findItem(R.id.nav_drawer_01);
                menuItem.setTitle(contextString);
            } else if(length == 2) {
                MenuItem menuItem = navMenu.findItem(R.id.nav_drawer_02);
                menuItem.setTitle(contextString);
            } else if(length == 3) {
                MenuItem menuItem = navMenu.findItem(R.id.nav_drawer_03);
                menuItem.setTitle(contextString);
            } else if(length == 4) {
                MenuItem menuItem = navMenu.findItem(R.id.nav_drawer_04);
                menuItem.setTitle(contextString);
            } else if(length == 5) {
                MenuItem menuItem = navMenu.findItem(R.id.nav_drawer_05);
                menuItem.setTitle(contextString);
            } else {
                break;
            }
        }

        View headerLayout  = navigationView.inflateHeaderView(R.layout.nav_header_main);
        ImageView imageView = (ImageView) headerLayout.findViewById(R.id.header_imageView);
        TextView nickname = (TextView) headerLayout.findViewById(R.id.header_nickname_textView);
        TextView account = (TextView) headerLayout.findViewById(R.id.header_account_textView);
        nickname.setText(showUser.getNickName());
        account.setText(showUser.getEmail());
        String iconString = showUser.getIconUrl();
        if(iconString.contains("0")){
            imageView.setImageResource(R.drawable.h000);
        } else if(iconString.contains("1")) {
            imageView.setImageResource(R.drawable.h001);
        } else if(iconString.contains("2")) {
            imageView.setImageResource(R.drawable.h002);
        } else if(iconString.contains("3")) {
            imageView.setImageResource(R.drawable.h003);
        } else if(iconString.contains("4")) {
            imageView.setImageResource(R.drawable.h004);
        } else if(iconString.contains("5")) {
            imageView.setImageResource(R.drawable.h005);
        } else if(iconString.contains("6")) {
            imageView.setImageResource(R.drawable.h006);
        } else if(iconString.contains("7")) {
            imageView.setImageResource(R.drawable.h007);
        } else if(iconString.contains("8")) {
            imageView.setImageResource(R.drawable.h008);
        } else {
            imageView.setImageResource(R.drawable.h009);
        }

        navigationView.setNavigationItemSelectedListener(navSelected);

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

        init();

        buttonInit();

    }

    NavigationView.OnNavigationItemSelectedListener navSelected = new
            NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem item) {
                    int id = item.getItemId();
                    Content content = new Content();
                    if (item.getTitle().length()>0) {
                        if (id == R.id.nav_drawer_01) {
                            content = userContentList.get(0);
                        } else if (id == R.id.nav_drawer_02) {
                            content = userContentList.get(1);
                        } else if (id == R.id.nav_drawer_03) {
                            content = userContentList.get(2);
                        } else if (id == R.id.nav_drawer_04) {
                            content = userContentList.get(3);
                        } else {
                            content = userContentList.get(4);
                        }
                    }
                    Intent intent = new Intent(WingActivity.this, MarkerViewActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(ARG_PARAMContent, content);
                    intent.putExtras(bundle);
                    startActivity(intent);

                    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                    drawer.closeDrawer(GravityCompat.START);
                    return true;
                }
            };

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.main2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            if(locationGet){
                Intent intent  = new Intent(WingActivity.this, SendContextActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(ARG_PARAM, showUser);
                bundle.putDouble(PARAM_LAT,localLatitude);
                bundle.putDouble(PARAM_LOG,localLongitude);
                intent.putExtras(bundle);
                startActivity(intent);
            } else {
                Toast.makeText(this,"please open your location",Toast.LENGTH_SHORT).show();
            }

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(null != mLocationClient){
            mLocationClient.onDestroy();
        }
    }

    /********************操作地图相关的**************************************/

    private void init() {
        if(aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setOnMapLoadedListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);

        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式，参见类AMap。
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.clear();
    }

    private void addMarkersToMap() {
        if(contentList == null || contentList.size() == 0) return;
        markerRelationContentMap.clear();
        int i = 0;
        for(Content content : contentList) {
            i = i+1000;
            runThread(content, i);
        }
    }

    private void runThread(final Content content, final int time) {
        Thread thread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(time);
                    createMarker(content);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }

    private void createMarker(Content content) {
        LatLng latLng = new LatLng(content.getLatitude(),
                content.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        if(content.getContextType() == ContextType.STUDY) {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        } else if(content.getContextType() == ContextType.SUPPORT) {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
        } else if(content.getContextType() == ContextType.SHARE) {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
        } else if(content.getContextType() == ContextType.COMMUNITY) {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        } else if(content.getContextType() == ContextType.ADVISE) {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
        } else if(content.getContextType() == ContextType.CONSULT) {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        } else {
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
        }
        markerOptions .snippet(content.getContext())
                .position(latLng)
                .draggable(false);
        Marker marker = aMap.addMarker(markerOptions);
        //保存content,让它与marker关联。待markerClick时使用
        markerRelationContentMap.put(marker,content);
    }

    @Override
    public void onMapLoaded() {
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {
        return false;
    }

    /**
     * 监听点击infowindow窗口事件回调
     */
    @Override
    public void onInfoWindowClick(Marker marker) {
        if(markerRelationContentMap.containsKey(marker)) {
            Intent intent = new Intent(this, MarkerViewActivity.class);
            Bundle bundle = new Bundle();
            Content content = markerRelationContentMap.get(marker);
            bundle.putSerializable(ARG_PARAMContent, content);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    private void buttonInit(){
        Button redFilter = (Button) findViewById(R.id.button_red_filter);
        redFilter.setOnClickListener(filterClick);
        Button orangeFilter = (Button) findViewById(R.id.button_orange_filter);
        orangeFilter.setOnClickListener(filterClick);
        Button yellowFilter = (Button) findViewById(R.id.button_yellow_filter);
        yellowFilter.setOnClickListener(filterClick);
        Button greenFilter = (Button) findViewById(R.id.button_green_filter);
        greenFilter.setOnClickListener(filterClick);
        Button blueFilter = (Button) findViewById(R.id.button_blue_filter);
        blueFilter.setOnClickListener(filterClick);
        Button cyanFilter = (Button) findViewById(R.id.button_cyan_filter);
        cyanFilter.setOnClickListener(filterClick);
        Button purpleFilter = (Button) findViewById(R.id.button_purple_filter);
        purpleFilter.setOnClickListener(filterClick);
    }

    private Button.OnClickListener filterClick = new Button.OnClickListener(){
        @Override
        public void onClick(View v){
            switch (v.getId()) {
                case R.id.button_red_filter:
                    contextType = ContextType.STUDY;
                    break;
                case R.id.button_orange_filter:
                    contextType = ContextType.SUPPORT;
                    break;
                case R.id.button_yellow_filter:
                    contextType = ContextType.SHARE;
                    break;
                case R.id.button_green_filter:
                    contextType = ContextType.COMMUNITY;
                    break;
                case R.id.button_blue_filter:
                    contextType = ContextType.ADVISE;
                    break;
                case R.id.button_cyan_filter:
                    contextType = ContextType.CONSULT;
                    break;
                default:
                    contextType = ContextType.OTHER;
                    break;
            }

            aMap.clear();
            CircleOptions circleOptions =new CircleOptions().
                    center(new LatLng(localLatitude,localLongitude))
                    .radius(showUser.getScope())
                    .strokeColor(R.color.button_normal)
                    .fillColor(R.color.cover_circle)
                    .strokeWidth(3);
            aMap.addCircle(circleOptions);
            contentList = mainBizReqService.filterType(contextType,allMapLocation.getLatitude(),
                    allMapLocation.getLongitude(), showUser.getShowUserId());
            addMarkersToMap();

        }
    };

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if ( amapLocation.getErrorCode() == 0) {
                locationGet =true;
                localLatitude = amapLocation.getLatitude();
                localLongitude = amapLocation.getLongitude();
                aMap.clear();
                CircleOptions circleOptions =new CircleOptions()
                        .center(new LatLng(localLatitude,localLongitude))
                        .radius(showUser.getScope())
                        .strokeColor(R.color.button_normal)
                        .fillColor(R.color.cover_circle)
                        .strokeWidth(3);
                aMap.addCircle(circleOptions);

                if(allType) {
                    contentList = mainBizReqService.searchScope(amapLocation.getLatitude(),
                            amapLocation.getLongitude(), showUser.getShowUserId());
                } else {
                    contentList = mainBizReqService.filterType(contextType,allMapLocation.getLatitude(),
                            allMapLocation.getLongitude(), showUser.getShowUserId());
                }
                addMarkersToMap();
                allMapLocation = amapLocation;
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点

                MyLocationStyle myLocationStyle = new MyLocationStyle();
                myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                        fromResource(R.drawable.location_marker));
                myLocationStyle.radiusFillColor(0);
                myLocationStyle.strokeWidth(0);
                aMap.setMyLocationStyle(myLocationStyle);
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr",errText);

            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(this);
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(1000*60*5);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

}